<?php

declare (strict_types=1);
namespace App\Model;

use Lete\Base\Abstraction\Model;
use Qbhy\HyperfAuth\Authenticatable;

/**
 * @property int $id
 * @property string $username
 * @property string $password
 * @property string $salt
 * @property string $name
 * @property string $avatar
 * @property int $role_id
 * @property string $last_ip
 * @property int $last_at
 * @property boolean $user_status
 * @property array $menu_permissions
 * @property int operator_id
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property \Carbon\Carbon $deleted_at
 */
class AdminUser extends Model implements Authenticatable
{
    const UPDATED_AT = null;

    public function getId()
    {
        return $this->getKey();
    }

    public static function retrieveById($key): ?Authenticatable
    {
        return self::findFromCache($key);
    }

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'admin_users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'role_id' => 'integer',
        'user_status' => 'boolean',
        'menu_permissions' => 'array',
        'operator_id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
        ''
    ];

    /**
     * 默认隐藏的字段
     * @var array
     */
    protected $hidden = ['password', 'salt'];

    /**
     * 字段默认值
     * @var array
     */
    protected $attributes = [
        'user_status' => 1,
    ];

    /**
     * 登录时间转换
     * @param $value
     * @return string
     */
    public function getLastAtAttribute($value)
    {
        return $this->toDateTimeString($value);
    }

    /**
     * 设置密码
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        if (!$this->salt) {
            $this->salt = rand(1, 9999);
        }
        $this->attributes['password'] = md5(strtolower($value). $this->salt);
    }

    /**
     * 关联角色
     * @return \Hyperf\Database\Model\Relations\HasOne
     */
    public function adminRole()
    {
        return $this->hasOne(AdminRole::class, 'id', 'role_id');
    }

    /**
     * @return \Hyperf\Database\Model\Relations\HasOne
     */
    public function operator()
    {
        return $this->hasOne(AdminUser::class, 'id', 'operator_id');
    }
}
